import { Injectable, NotFoundException } from '@nestjs/common';
import { UpdateArticleDto } from './dto/update-article.dto';
import { Article } from './entities/article.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateArticleDto } from './dto/create-article.dto';
import { QueryArticleDto } from './dto/query-article.dto';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article)
    private articleRepository: Repository<Article>,
  ) {}

  async create(createArticleDto: CreateArticleDto) {
    console.log(
      'article.controller.ts-create-createArticleDto',
      createArticleDto,
    );

    const newArticle = this.articleRepository.create(createArticleDto);
    //

    // 保存到数据库
    await this.articleRepository.save(newArticle);
    return {
      data: createArticleDto,
    };
  }

  async findAll(query: QueryArticleDto) {
    console.log('article.service.ts-findAll-query', query);
    // 获取所有文章
    return {
      data: {
        articleList: await this.articleRepository.find(),
      },
    };
  }

  async findOne(id: string) {
    // 根据id获取单个文章
    const article = await this.articleRepository.findOne({
      where: {
        id,
      },
      relations: ['tags', 'sort'],
    });
    if (!article) {
      throw new NotFoundException(`Article with ID "${id}" not found`);
    }
    return {
      data: {
        article,
      },
    };
  }

  async update(
    id: string,
    updateArticleDto: UpdateArticleDto,
  ): Promise<Article> {
    // 首先检查文章是否存在
    const article = await this.articleRepository.findOne({
      where: {
        id,
      },
    });
    if (!article) {
      throw new NotFoundException(`Article with ID "${id}" not found`);
    }
    // 更新文章字段
    this.articleRepository.merge(article, updateArticleDto);
    await this.articleRepository.save(article);
    return article;
  }

  async remove(id: string): Promise<void> {
    // 根据id删除文章
    const result = await this.articleRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException(`Article with ID "${id}" not found`);
    }
  }
}
